/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.satish.gmailapp.filters;

import com.satish.gmailapp.beans.User;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.satish.gmailapp.constants.WebConstants.*;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *
 * @author satish
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = {"/faces/*"})
public class LoginFilter implements Filter {

    private static final Logger logger = LogManager.getLogger(LoginFilter.class);
    
    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) request;
        final HttpSession session = req.getSession();
        
        logger.debug("Path: " + req.getServletPath());
        
        final User user = (User) session.getAttribute(USER);
        final String servletPath = req.getServletPath();
        final boolean isLoginPage = servletPath.endsWith("login.xhtml");
        boolean isResource = req.getServletPath().contains("javax.faces.resource") || req.getServletPath().contains("faces/js/");
        
        if (user != null && user.getLoggedIn() || isLoginPage || isResource) {
            chain.doFilter(request, response);
        } else {
            HttpServletResponse res = (HttpServletResponse) response;
            
            logger.debug("Redirecting to login page");
            logger.debug("Setting redirect uri in session: " + getFullUrl(req));
            
            session.setAttribute(REDIRECT_URI, getFullUrl(req));
            res.sendRedirect(req.getContextPath() + "/faces/login.xhtml");
        }
    }

    @Override
    public void destroy() {
    }

    private String getFullUrl(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();

        if (queryString == null) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }
}